<template>
  <el-dialog
    :title="title"
    :visible.sync="visibleSync"
    @close="onClose"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :inline="true" ref="planCardForm" class="demo-form-inline">
      <el-form-item label="计划类型：">
        <el-select v-model="planType.value" placeholder="计划类型" :disabled="leaderCheckState===1">
          <el-option
            v-for="(option) in planType.options"
            :label="option.label"
            :value="option.value"
            :key="option.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属业务组：">
        <el-select v-model="planGroup.value" placeholder="所属业务组" :disabled="leaderCheckState===1">
          <el-option
            v-for="(option, idx) in planGroup.options"
            :label="option.label"
            :value="option.value"
            :key="idx"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="planType.value === 2" label="计划年度：">
        <el-date-picker
          v-model="planYear.value"
          type="year"
          format="yyyy"
          value-format="yyyy"
          placeholder="计划年度"
          :disabled="leaderCheckState===1"
        ></el-date-picker>
      </el-form-item>
      <el-form-item v-else-if="planType.value === 1" label="计划月度：">
        <el-date-picker
          v-model="planMonth.value"
          type="month"
          format="yyyy-MM"
          value-format="yyyy-MM"
          placeholder="计划月度"
          :disabled="leaderCheckState===1"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="推进落实人：">
        <el-select
          v-model="tuijinUser.value"
          filterable
          placeholder="输入/选择推进落实人"
          multiple
          :disabled="leaderCheckState===1"
        >
          <el-option
            v-for="(option) in tuijinUser.options"
            :value="option.label"
            :key="option.label"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划名称：">
        <el-input v-model="planTitle" placeholder="计划名称" :disabled="leaderCheckState===1"></el-input>
      </el-form-item>
      <el-form-item label="牵头负责人：">
        <el-select
          v-model="qiantouUser.value"
          filterable
          placeholder="输入/选择牵头负责人"
          multiple
          :disabled="leaderCheckState===1"
        >
          <el-option
            v-for="(option) in qiantouUser.options"
            :value="option.label"
            :key="option.label"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn-cell">
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="leaderCheckState===1"
        @click="addStep"
      >添加推进步骤</el-button>
    </div>
    <el-form :inline="true" class="demo-form-inline">
      <template v-for="(item, idx) in steps">
        <div :key="'step' + idx">
          <el-form-item label="推进步骤：">
            <el-input
              placeholder="输入推进步骤"
              :disabled="leaderCheckState===1"
              v-model="item.step_title"
            ></el-input>
          </el-form-item>
          <el-form-item label="完成时限：">
            <el-date-picker
              v-model="item.complate_date"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :disabled="leaderCheckState===1"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="进度：">
            <el-input-number
              v-model="item.step_progress"
              placeholder="请输入百分比"
              style="width:150px;"
              :max="100"
              :min="0"
              controls-position="right"
            ></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              v-if="leaderCheckState!==1"
              icon="el-icon-delete"
              @click="deleteStep(idx, item.id)"
            >删除</el-button>
          </el-form-item>
        </div>
      </template>
    </el-form>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="提交组长：">
        <el-select
          v-model="groupLeader.value"
          placeholder="输入/选择提交组长"
          filterable
          :disabled="leaderCheckState===1"
        >
          <el-option
            v-for="(option, idx) in groupLeader.options"
            :label="option.label"
            :value="option.value"
            :key="idx"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form class="footer">
      <el-form-item>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
// const PLAN_GROUP = 'PLAN_GROUP'
// const TUIJIN_USER = 'TUIJIN_USER'
// const QIANTOU_USER = 'QIANTOU_USER'
// const GROUP_LEADER = 'GROUP_LEADER'

export default {
  name: 'PlanCard',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    mode: {
      type: String,
      default: 'add'
    }
  },
  watch: {
    visible(value) {
      this.visibleSync = value
    },
    data(value) {
      this.initPlanInfo(value)
    }
  },
  data() {
    const yearOptions = []
    const monthOptions = []
    for (let i = 0; i < 12; i++) {
      const value = i + 1;
      monthOptions.push({
        label: value + '月',
        value: value
      })
    }

    return {
      visibleSync: false,
      planId: '',
      planType: {
        value: '',
        options: [{
          label: '月度',
          value: 1
        }, {
          label: '年度',
          value: 2
        }]
      },
      planGroup: {
        value: '',
        options: []
      },
      planYear: {
        value: '',
        options: yearOptions
      },
      planMonth: {
        value: '',
        options: monthOptions
      },
      tuijinUser: {
        value: [],
        cache: [],
        options: []
      },
      planTitle: '',
      qiantouUser: {
        value: [],
        cache: [],
        options: []
      },
      steps: [],
      groupLeader: {
        value: '',
        options: []
      },
      leaderCheckState: 0
    }
  },
  methods: {
    onClose() {
      this.$emit('close')
    },
    initPlanInfo(value) {
      this.planId = value.planId || ''
      this.planType.value = value.planType || ''
      this.planTitle = value.planTitle || ''
      this.planYear.value = value.planYear || ''
      this.planMonth.value = value.planMonth || ''
      this.planGroup.value = value.planGroupId || ''
      this.steps = value.steps || []
      // 这些在提交的时候，可能需要根据值去匹配 ID
      this.qiantouUser.value = this.qiantouUser.cache = value.qtUserNames ? value.qtUserNames.split(',') : []
      this.tuijinUser.value = this.tuijinUser.cache = value.zrUserNames ? value.zrUserNames.split(',') : []
      this.groupLeader.value = value.teamCheckUser || ''

      this.leaderCheckState = value.leaderCheckState || 0
    },
    submit() {
      // select 全部用 label，最终提交时找寻 value 来处理 ID 值。

      let qtUserValue = this.qiantouUser.value
      let qtUserIds = []
      let qtUserNames = []
      // 修改操作时，可能没有变化。
      if (qtUserValue.length) {
        if (qtUserValue.toString() === this.qiantouUser.cache.toString()) {
          qtUserIds = this.data.qtUserIds
          qtUserNames = this.data.qtUserNames
        } else {
          this.qiantouUser.options.map(item => {
            if (qtUserValue.includes(item.label)) {
              qtUserIds.push(item.value)
              qtUserNames.push(item.label)
            }
          })
        }
      }

      let tjUserValue = this.tuijinUser.value
      let zrUserIds = []
      let zrUserNames = []
      if (tjUserValue.length) {
        if (tjUserValue.toString() === this.tuijinUser.cache.toString()) {
          zrUserIds = this.data.zrUserIds
          zrUserNames = this.data.zrUserNames
        } else {
          this.qiantouUser.options.map(item => {
            if (tjUserValue.includes(item.label)) {
              zrUserIds.push(item.value)
              zrUserNames.push(item.label)
            }
          })
        }
      }

      let params = {
        planType: this.planType.value,
        planTitle: this.planTitle,
        planGroupId: this.planGroup.value,
        qtUserNames: qtUserNames.toString(),
        qtUserIds: qtUserIds.toString(),
        zrUserNames: zrUserNames.toString(),
        zrUserIds: zrUserIds.toString(),
        teamCheckUser: this.groupLeader.value,
        steps: this.steps
      }
      if (params.planType === 1) {
        const monthValue = this.planMonth.value
        params.planMonth = monthValue
        params.planYear = monthValue.split('-')[0]
      } else if (params.planType === 2) {
        params.planYear = this.planYear.value
      }

      const keys = []
      for (let key in params) {
        keys.push(key)
      }
      let validated = true
      for (let i = 0; i < keys.length; i++) {
        if (params[keys[i]] instanceof Array) {
          if (!params[keys[i]].length) {
            validated = false
            this.$message.error('请填写推进步骤信息')
            break
          }
        } else {
          if (!params[keys[i]]) {
            validated = false
            this.$message.error('请填写完整的信息')
            break
          }
        }
      }

      if (validated) {
        if (this.mode === 'add') {
          this.addPlan(params)
        } else {
          params.planId = this.data.planId
          this.updatePlan(params)
        }
      }
    },
    close() {
      this.visibleSync = false
    },
    addPlan(params) {
      utils.post('plan/addSave', params, res => {
        if (res.success) {
          this.clearForm()
          this.$emit('submit')
          this.close()
        }
      })
    },
    updatePlan(params) {
      utils.post('plan/editSave', params, res => {
        if (res.success) {
          this.clearForm()
          this.$emit('submit')
          this.close()
        }
      })
    },
    addStep() {
      this.steps.push({
        id: '',
        step_title: '',
        complate_date: '',
        step_progress: ''
      })
    },
    deleteStep(index, id) {
      if (id) {
        utils.post('plan/deleteSetp', {
          id
        }, res => {
          if (res.success) {
            this.steps.splice(index, 1)
          }
        })
      } else {
        this.steps.splice(index, 1)
      }
    },
    initGroupList() {
      const GROUP_LIST = 'GROUP_LIST'
      const cacheData = localStorage.getItem(GROUP_LIST)
      if (cacheData) {
        this.planGroup.options = JSON.parse(cacheData)
      } else {
        utils.post(utils.api.politicalWorkPlan.groupNameList, {}, res => {
          if (res.success) {
            const options = res.data.map(item => {
              return {
                label: item.planGroupName,
                value: item.planGroupId
              }
            })
            this.planGroup.options = options
            localStorage.setItem(GROUP_LIST, JSON.stringify(this.planGroup.options))
          }
        })
      }
    },
    initQiantouUserList() {
      this.fetchUserList(1, data => {
        const options = data.map(item => {
          return {
            label: item.user_name,
            value: item.user_id
          }
        })
        this.qiantouUser.options = options
        this.tuijinUser.options = options
      })
    },
    initGroupLeaderList() {
      this.fetchUserList(2, data => {
        const options = data.map(item => {
          return {
            label: item.user_name,
            value: item.user_id
          }
        })
        this.groupLeader.options = options
      })
    },
    fetchUserList(userType, callback) {
      // TODO 本地缓存的数据，应该在页面中统一完成，这里只需读取。
      utils.get('plan/planUserList' + '?userType=' + userType, res => {
        if (res.success) {
          callback(res.data)
        }
      })
    },
    clearForm() {
      // 重置表单
      this.initPlanInfo({})
    }
  },
  created() {
    this.visibleSync = this.visible
    this.initGroupList()
    this.initQiantouUserList()
    this.initGroupLeaderList()
  }
}
</script>
<style lang="less">
@primary-color: #cb2c21;
.el-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #dddddd;
    padding-bottom: 0;
    .el-dialog__title {
      border-bottom: 3px solid @primary-color;
    }
  }
  .btn-cell {
    margin-bottom: 20px;
  }
  .footer {
    text-align: center;
  }
}
</style>